<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <!-- 品牌  -->
    <div class="item">
      <div class="head">品牌：</div>
      <div class="body">
        <a
          href="javascript:;"
          :class="{ active: !SubFilterList.select }"
          @click="SubFilterList.select = ''"
          >全部</a
        >
        <a
          href="javascript:;"
          v-for="i in SubFilterList.brands"
          :key="i.id"
          @click="SubFilterList.select = i.id"
          :class="{ active: SubFilterList.select === i.id }"
          >{{ i.name }}</a
        >
      </div>
    </div>
    <!-- 规格属性 -->
    <div class="item" v-for="i in SubFilterList.saleProperties" :key="i.id">
      <div class="head">{{ i.name }}：</div>
      <div class="body">
        <a
          href="javascript:;"
          @click="i.select = ''"
          :class="{ active: !i.select }"
          >全部</a
        >
        <a
          href="javascript:;"
          v-for="sub in i.properties"
          :key="sub.id"
          :class="{ active: i.select === sub.id }"
          @click="i.select = sub.id"
          >{{ sub.name }}</a
        >
      </div>
    </div>
  </div>
</template>
<script>
import { categorySubFilter } from '@/api/category'
import { onBeforeRouteLeave, useRoute } from 'vue-router'
import { ref, watch } from 'vue-demi'
export default {
  name: 'SubFilter',
  setup (props, { emit }) {
    const route = useRoute()
    const SubFilterList = ref({})
    const stopSubFilter = watch(
      () => route.params.id,
      newVal => {
        categorySubFilter(newVal).then(res => {
          SubFilterList.value = res.result
        })
      },
      {
        immediate: true
      }
    )
    onBeforeRouteLeave((to, from) => {
      stopSubFilter()
    })
    watch(
      () => SubFilterList.value,
      newVal => {
        if (newVal.id) {
          const brandId = newVal.select || ''
          const attrs = newVal.saleProperties.map(i => {
            return {
              groupName: i.name,
              propertyName:
                (i.select &&
                  i.properties.find(i2 => i2.id === i.select).name) ||
                ''
            }
          })
          const temp = { brandId, attrs }

          emit('change', temp)
        }
      },
      { immediate: true, deep: true }
    )
    return { SubFilterList }
  }
}
</script>
<style scoped lang="less">
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
